import { useEditorStore } from '@/stores/editor'
import useSaveWork from '@/hooks/useSaveWork'
import html2canvas from 'html2canvas'
import { uploadFile } from '@/service/request'

export default function usePublishWork() {
  const editor = useEditorStore()

  const route = useRoute()

  const channels = computed(() => editor.channels)
  const currentWorkId = route.params.id as string
  const isPublishing = ref(false)

  const { saveWork } = useSaveWork(true)

  function getCanvasBlob(canvas: HTMLCanvasElement) {
    return new Promise<Blob | null>(resolve => {
      canvas.toBlob(blob => {
        resolve(blob)
      })
    })
  }

  async function screenshotAndUpload(el: HTMLElement) {
    // scale 默认是 window.devicePixelRatio 的值，在retina屏上为2或者在低分频率屏幕下为0.5，这边要保证截图宽度的一致性（375）, 设置固定像素比 scale: 1
    const canvas = await html2canvas(el, { width: 375, useCORS: true, scale: 1 })
    const canvasBlob = await getCanvasBlob(canvas)
    if (canvasBlob) {
      const data = await uploadFile('utils/upload-img', canvasBlob)
      return data
    }
  }

  const publishWork = async (el: HTMLElement) => {
    isPublishing.value = true
    try {
      // 截图并且上传
      const rawData = await screenshotAndUpload(el)
      if (rawData) {
        // console.log(rawData.data.url)
        // 更新 coverImg 字段
        editor.updatePage({ key: 'coverImg', value: rawData.data.url, isRoot: true })
        // 保存作品
        await saveWork()
        // 发布作品
        await editor.publishWork(currentWorkId)
        // 获取渠道列表
        await editor.fetchChannels(currentWorkId)
        // 如果该作品没有渠道，需要默认创建一个渠道
        if (channels.value.length === 0) {
          await editor.createChannels({ name: '默认', workId: parseInt(currentWorkId) })
        }
      }
    } catch (error) {
      console.error(error)
    } finally {
      isPublishing.value = false
    }
  }

  return {
    isPublishing,
    publishWork
  }
}
